<?php

namespace App\Http\Controllers\Backstage\Encyclopedia;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Backstage\Encyclopedia\Category\CreateRequest;
use App\Http\Requests\Backstage\Encyclopedia\Category\UpdateRequest;
use App\Models\Encyclopedia\Category;
use App\Transformers\Encyclopedia\CategoryTransformer;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{

    /**
     * @var Category
     */
    protected $model;

    public function __construct(Category $category)
    {
        $this->model = $category;
    }

    public function index()
    {
        $page_size = get_request_page();
        $params = \request()->all();
        $model = $this->model->where(function ($query) use ($params) {
            if ($name = array_get($params, 'name')) {
                $query->where('name', 'like', "%{$name}%");
            }
        });
        if ($page_size) {
            $models = $model->paginate($page_size);
            return $this->response->paginator($models, new CategoryTransformer());
        }
        return $this->response->collection($model->get(), new CategoryTransformer());
    }

    /**
     * @param CreateRequest $request
     * @return \Dingo\Api\Http\Response
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            $attributes['author_id'] = \Auth::user()->id;
            $model = Category::create($attributes);
            return $model;
        });
        $location = dingo_route('v1', 'backstage.encyclopedia.category.show', $model->id);
        return $this->response->item($model, new CategoryTransformer())
            ->withHeader('Loccation', $location)
            ->setStatusCode(201);
    }

    public function show($id)
    {
        //
    }

    /**
     * @param UpdateRequest $request
     * @param $id
     * @return \Dingo\Api\Http\Response
     * @throws \Throwable
     */
    public function update(UpdateRequest $request, $id)
    {
        \DB::transaction(function () use ($request, $id) {
            $attributes = $request->validated();
            $model = Category::find($id);
            $model->update($attributes);
            return $model;
        });
        return $this->response->noContent();
    }

    public function destroy($id)
    {
        if ($model = Category::whereId($id)->first()) {
            $model->delete();
        }
        return $this->response->noContent();
    }
}
